package com.fourth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fourth.dao.UbCartDao;
import com.fourth.dao.UbCommentDao;
import com.fourth.service.UbCartService;
import com.fourth.service.UbCommentService;
import com.fourth.util.GetUidUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ljx.entity.Cart;
import com.ljx.entity.Comment;
import com.ljx.entity.Goods;
import com.ljx.entity.Order;
import com.ljx.security.util.WebUtils;
import com.ljx.utils.JwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Mr.ma
 * @since 2023/3/2 14:40
 **/
@Service
public class UbCartServiceImpl implements UbCartService {
    @Resource
    private UbCartDao ubCartDao;


    @Override
    public PageInfo<Cart> findCart(Integer currentPage,Integer pageSize) {
        String uid = GetUidUtil.getUid();
        PageHelper.startPage(currentPage,pageSize);
        List<Cart> carts = ubCartDao.findCart(uid);
        PageInfo<Cart> pageInfo = new PageInfo<>(carts);
        return pageInfo;
    }

    @Override
    public int insert(Cart cart) {
        String uid = GetUidUtil.getUid();
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("uid",uid);
        wrapper.eq("goods_id",cart.getGoodsId());
        wrapper.eq("is_deleted",0);
        Cart oldCart = ubCartDao.selectOne(wrapper);
        if(oldCart != null) {
            oldCart.setNum(oldCart.getNum() + cart.getNum());
            return ubCartDao.updateById(oldCart);
        }
        cart.setUid(uid);
        cart.setIsDeleted(0);
        return ubCartDao.insert(cart);
    }

    @Override
    public int deleteCart(String id) {
        int delete = ubCartDao.deleteById(id);
        return delete;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteByIds(String[] ids) {
        int i = ubCartDao.deleteBatchIds(Arrays.asList(ids));
        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteCartByList(List<Cart> cartList) {
        List<String> idList = cartList.stream().map(item -> item.getId()).collect(Collectors.toList());
        return ubCartDao.deleteBatchIds(idList);
    }

    @Override
    public int deleteCartByUidAndGoodsId(String uid, String goodsId) {
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("uid",uid);
        wrapper.eq("goods_id",goodsId);
        return ubCartDao.delete(wrapper);
    }
}
